package org.xg.store;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.xg.bean.ChatMessages;

import java.util.LinkedList;
import java.util.List;

/**
 * @author hans
 * @date 2025/05/09 11:34
 * @description MongoDB 持久化聊天记录功能，即自定义实现 ChatMemoryStore
 */
@Component
public class MongoChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取聊天记录
     *
     * @param memoryId 聊天记录的ID
     * @return 聊天记录列表
     */
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);
        if (null == chatMessages) {
            return new LinkedList<>();
        }
        String contentJson = chatMessages.getContent();
        return ChatMessageDeserializer.messagesFromJson(contentJson);
    }

    /**
     * 更新聊天记录
     *
     * @param memoryId 聊天记录的ID
     * @param list     聊天记录列表
     */
    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);

        Update update = new Update();
        // 将聊天记录列表转化为JSON
        String messagesJson = ChatMessageSerializer.messagesToJson(list);
        update.set("content", messagesJson);

        mongoTemplate.upsert(query, update, ChatMessages.class);
    }

    /**
     * 通过聊天记录的ID，删除聊天记录
     *
     * @param memoryId 聊天记录的ID
     */
    @Override
    public void deleteMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        mongoTemplate.remove(query, ChatMessages.class);
    }
}
